<template>
	<view class="profile-container">
		<!-- 用户信息区域 -->
		<view class="profile-header">
			<view class="header-bg">
				<image class="bg-image" src="/static/images/profile-bg.jpg" mode="aspectFill" />
				<view class="header-overlay"></view>
			</view>

			<view class="user-info">
				<view class="avatar-section" @click="changeAvatar">
					<image class="user-avatar" :src="avatarSrc" mode="aspectFill" @error="onAvatarError" />
					<view class="avatar-edit">
						<text class="edit-icon">📷</text>
					</view>
				</view>

				<view class="user-details">
					<text class="user-name">{{ userInfo.nickname || userInfo.username || '未设置昵称' }}</text>
					<text class="user-role" @click="goToLogin">{{ getRoleText(userInfo.role) }}</text>
					<text class="user-ship" v-if="userInfo.shipName">{{ userInfo.shipName }}</text>
				</view>

				<view class="edit-profile" @click="editProfile">
					<text class="edit-text">编辑资料</text>
					<text class="edit-arrow">></text>
				</view>
			</view>
		</view>

		<!-- 数据统计区域 -->
		<view class="stats-section">
			<view class="stats-grid">
				<view class="stats-item" @click="goToOrders">
					<text class="stats-number">{{ userStats.orderCount }}</text>
					<text class="stats-label">订单数量</text>
				</view>
				<view class="stats-item" @click="goToFavorites">
					<text class="stats-number">{{ userStats.favoriteCount }}</text>
					<text class="stats-label">收藏商品</text>
				</view>
				<view class="stats-item" @click="goToCoupons">
					<text class="stats-number">{{ userStats.couponCount }}</text>
					<text class="stats-label">优惠券</text>
				</view>
				<view class="stats-item" @click="goToPoints">
					<text class="stats-number">{{ userStats.pointBalance }}</text>
					<text class="stats-label">积分余额</text>
				</view>
			</view>
		</view>

		<!-- 订单快捷入口 -->
		<view class="order-section">
			<view class="section-header">
				<text class="section-title">我的订单</text>
				<text class="section-more" @click="goToOrders">查看全部</text>
			</view>

			<view class="order-shortcuts">
				<view class="order-item" @click="goToOrders('pending')">
					<view class="order-icon">
						<text class="icon">💰</text>
						<view v-if="orderCounts.pending > 0" class="badge">{{ orderCounts.pending }}</view>
					</view>
					<text class="order-text">待付款</text>
				</view>
				<view class="order-item" @click="goToOrders('shipped')">
					<view class="order-icon">
						<text class="icon">🚢</text>
						<view v-if="orderCounts.shipped > 0" class="badge">{{ orderCounts.shipped }}</view>
					</view>
					<text class="order-text">待收货</text>
				</view>
				<view class="order-item" @click="goToOrders('completed')">
					<view class="order-icon">
						<text class="icon">✅</text>
					</view>
					<text class="order-text">已完成</text>
				</view>
				<view class="order-item" @click="goToOrders('refund')">
					<view class="order-icon">
						<text class="icon">🔄</text>
						<view v-if="orderCounts.refund > 0" class="badge">{{ orderCounts.refund }}</view>
					</view>
					<text class="order-text">退换货</text>
				</view>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="menu-section">


			<view class="menu-group">
				<text class="group-title">客户服务</text>
				<view class="menu-list">
					<view class="menu-item" @click="goToCustomerService">
						<view class="menu-left">
							<text class="menu-icon">🎧</text>
							<text class="menu-text">在线客服</text>
						</view>
						<text class="menu-arrow">></text>
					</view>
				</view>
			</view>

			<view class="menu-group">
				<text class="group-title">身份认证</text>
				<view class="menu-list">
					<view class="menu-item" @click="goToIdentityVerification">
						<view class="menu-left">
							<text class="menu-icon">🆔</text>
							<text class="menu-text">实名认证</text>
						</view>
						<view class="menu-right">
							<text class="status-badge" :class="getVerificationStatusClass(userInfo.verificationStatus)">
								{{ getVerificationStatusText(userInfo.verificationStatus) }}
							</text>
							<text class="menu-arrow">></text>
						</view>
					</view>
				</view>
			</view>

			<view class="menu-group">
				<text class="group-title">系统设置</text>
				<view class="menu-list">
					<view class="menu-item" @click="goToSettings">
						<view class="menu-left">
							<text class="menu-icon">⚙️</text>
							<text class="menu-text">系统设置</text>
						</view>
						<text class="menu-arrow">></text>
					</view>
					<view class="menu-item" @click="goToAbout">
						<view class="menu-left">
							<text class="menu-icon">ℹ️</text>
							<text class="menu-text">关于我们</text>
						</view>
						<text class="menu-arrow">></text>
					</view>
				</view>
			</view>
		</view>

		<!-- 退出登录 -->
		<view class="logout-section">
			<button class="logout-btn" @click="logout">
				<text class="logout-text">退出登录</text>
			</button>
		</view>

		<!-- 版本信息 -->
		<view class="version-info">
			<text class="version-text">版本 v1.0.0</text>
		</view>

		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted, onUnmounted, watchEffect } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getEnv } from '../../utils/env.js'
import userApi from '../../api/user.js'
import orderApi from '../../api/order.js'
import favoriteApi from '../../api/favorite.js'
import identityApi from '../../api/identity.js'

// 全局状态
const store = inject('$store')

// 响应式数据
const isLoading = ref(false)

// 自动刷新相关
const autoRefreshTimer = ref(null)
const isPageVisible = ref(true)
const userStats = ref({
	orderCount: 0,
	favoriteCount: 0,
	couponCount: 0,
	pointBalance: 0
})
const orderCounts = ref({
	pending: 0,
	shipped: 0,
	completed: 0,
	refund: 0
})

// 计算属性
const userInfo = computed(() => store.state.userInfo || {})

// 头像显示：过滤历史占位值(identity_verified)，并规范为绝对URL；不回退默认图
const resolveAvatar = (raw) => {
  const url = (raw || '').toString().trim()
  // 兼容历史脏数据：avatar 被写成 'identity_verified' 时返回空，避免发起 /identity_verified 请求
  if (!url || url === 'identity_verified') return ''
  if (url.startsWith('http')) return url
  const base = getEnv('VUE_APP_BASE_API', '')
  const path = url.startsWith('/') ? url : `/${url}`
  return base ? `${base}${path}` : path
}
const avatarSrc = computed(() => resolveAvatar(userInfo.value?.avatar))
const onAvatarError = () => { /* 出错时保持空字符串，不回退默认图 */ }

// 页面加载
onMounted(() => {
	loadUserData()
	startAutoRefresh() // 启动自动刷新

	// 监听页面可见性变化

	document.addEventListener('visibilitychange', handleVisibilityChange)
})

// 页面卸载时清理定时器
onUnmounted(() => {
	stopAutoRefresh()
	document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 处理页面可见性变化
const handleVisibilityChange = () => {
  isPageVisible.value = !document.hidden
  if (isPageVisible.value) {
    // 页面变为可见时默默刷新
    loadUserData()
  }
}

// Tab 页返回时（如从个人资料返回“我的”），同步本地缓存，确保头像立即一致
onShow(() => {
  try {
    const cached = uni.getStorageSync('userInfo')
    if (cached && JSON.stringify(cached) !== JSON.stringify(store.state.userInfo || {})) {
      store.actions.setUserInfo(cached)
    }
  } catch (e) {
    // 忽略
  }
})

// 加载用户数据
const loadUserData = async () => {
	try {
		// 后台默默刷新，不显示任何加载状态

		// 并行加载用户资料、订单统计、收藏统计和实名认证状态
		const [userProfileResponse, orderStatsResponse, favoriteStatsResponse, identityStatusResponse] = await Promise.all([
			userApi.getUserProfile().catch(err => {
				console.warn('获取用户资料失败:', err)
				return null
			}),
			orderApi.getOrderStatistics().catch(err => {
				console.warn('获取订单统计失败:', err)
				return { total: 0, pending: 0, processing: 0, shipping: 0, completed: 0, exception: 0 }
			}),
			favoriteApi.getUserFavorites({ page: 1, size: 1 }).catch(err => {
				console.warn('获取收藏统计失败:', err)
				return { total: 0 }
			}),
			identityApi.getIdentityStatus().catch(err => {
				console.warn('获取实名认证状态失败:', err)
				return { status: 'not_verified' }
			})
		])

			// 同步用户资料到全局，确保头像等字段更新
			if (userProfileResponse && store.actions && store.actions.setUserInfo) {
				const merged = { ...(store.state.userInfo || {}), ...userProfileResponse }
				store.actions.setUserInfo(merged)
				try { uni.setStorageSync('userInfo', merged) } catch (e) {}
			}

    console.log('用户数据加载完成:', userProfileResponse, orderStatsResponse, favoriteStatsResponse, identityStatusResponse)
		// 更新用户统计数据
		if (orderStatsResponse) {
			userStats.value.orderCount = orderStatsResponse.data.total || 0
			// 更新各状态订单数量
			orderCounts.value = {
				pending: orderStatsResponse.pending || 0,
				shipped: (orderStatsResponse.processing || 0) + (orderStatsResponse.shipping || 0),
				completed: orderStatsResponse.completed || 0,
				refund: orderStatsResponse.exception || 0
			}
		}

		if (favoriteStatsResponse) {
			userStats.value.favoriteCount = favoriteStatsResponse.data.total || 0
		}

		// 更新实名认证状态 - 使用与认证页面相同的逻辑
		if (identityStatusResponse && store.actions && store.actions.setUserInfo) {
			const currentUserInfo = store.state.userInfo || {}

			// 解析认证状态，支持多种数据结构
			let verificationStatus = 'not_verified'

			if (identityStatusResponse.success || identityStatusResponse.status) {
				// 从 data 字段或根级别获取状态
				let statusData = identityStatusResponse.data || identityStatusResponse

				// 如果 data 字段为空，但根级别有认证信息
				if (!statusData || !statusData.status) {
					if (identityStatusResponse.status) {
						statusData = {
							status: identityStatusResponse.status,
							realName: identityStatusResponse.realName,
							isApproved: identityStatusResponse.isApproved
						}
					}
				}

				// 判断认证状态
				if (statusData) {
					if (statusData.status === 'approved' || statusData.isApproved === true) {
						verificationStatus = 'approved'
					} else if (statusData.status === 'pending') {
						verificationStatus = 'pending'
					} else if (statusData.status === 'rejected') {
						verificationStatus = 'rejected'
					} else {
						verificationStatus = 'not_verified'
					}
				}
			}

			store.actions.setUserInfo({
				...currentUserInfo,
				verificationStatus: verificationStatus
			})

			console.log('个人中心认证状态更新:', {
				originalResponse: identityStatusResponse,
				updatedStatus: verificationStatus
			})
		}

		// 设置默认值（暂时使用固定值）
		userStats.value.couponCount = userStats.value.couponCount || 0
		userStats.value.pointBalance = userStats.value.pointBalance || 0

	} catch (error) {
		console.error('加载用户数据失败:', error)
	} finally {
		// 后台刷新完成，无需显示状态
		isLoading.value = false
	}
}

// 启动自动刷新
const startAutoRefresh = () => {
	stopAutoRefresh() // 先清理旧的定时器

	// 设置定时刷新，每30秒刷新一次认证状态（减少频率）
	autoRefreshTimer.value = setInterval(() => {
		if (isPageVisible.value) {
			// 后台默默刷新，用户无感知
			loadUserData()
		}
	}, 300000) // 300秒刷新一次，大幅减少服务器压力
}

// 手动刷新状态
const refreshStatus = () => {
	console.log('用户手动刷新认证状态')
	loadUserData()
	// 后台默默刷新，不显示任何提示
}

// 停止自动刷新
const stopAutoRefresh = () => {
	if (autoRefreshTimer.value) {
		clearInterval(autoRefreshTimer.value)
		autoRefreshTimer.value = null
	}
}

// 获取角色文本
const getRoleText = (role) => {
	switch (role) {
		case 'captain':
			return '船长'
		case 'crew':
			return '船员'
		case 'individual':
			return '个人用户'
		default:
			return '用户'
	}
}

// 头像相关
const changeAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			try {
				uni.showLoading({
					title: '上传中...'
				})

				// 上传头像到后端
				const uploadResponse = await userApi.uploadAvatar(res.tempFilePaths[0])

				// 更新用户信息 - 使用后端返回的avatarUrl
				if (uploadResponse && uploadResponse.avatarUrl) {
					const updatedUserInfo = {
						...userInfo.value,
						avatar: uploadResponse.avatarUrl
					}

					// 更新全局状态
					store.actions.setUserInfo(updatedUserInfo)

					// 同步更新本地存储
					uni.setStorageSync('userInfo', updatedUserInfo)
				}

				uni.hideLoading()
				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				})
			} catch (error) {
				uni.hideLoading()
				console.error('上传头像失败:', error)
				uni.showToast({
					title: error.message || '上传失败',
					icon: 'none'
				})
			}
		}
	})
}

// 页面跳转
const editProfile = () => {
	uni.navigateTo({
		url: '/pages/profile/info?from=profile'
	})
}

const goToOrders = (status = '') => {
	// 根据状态参数构建 URL
	let url = '/pages/order/list'

	if (status) {
		// 将前端状态映射到后端状态码
		let statusCode = ''
		switch (status) {
			case 'pending':
				statusCode = '0' // 待付款
				break
			case 'shipped':
				statusCode = '1,2' // 配货中+送货中
				break
			case 'completed':
				statusCode = '3' // 已完成
				break
			case 'refund':
				statusCode = '4' // 异常/退换货
				break
		}

		if (statusCode) {
			url += `?status=${statusCode}`
		}
	}

	// 添加来源参数
	const urlWithSource = url.includes('?') ? `${url}&from=profile` : `${url}?from=profile`
	uni.navigateTo({ url: urlWithSource })
}

const goToFavorites = () => {
	uni.navigateTo({
		url: '/pages/favorites/list'
	})
}

const goToCoupons = () => {
	uni.navigateTo({
		url: '/pages/profile/coupons'
	})
}

const goToPoints = () => {
	uni.navigateTo({
		url: '/pages/profile/points'
	})
}

const goToShipManagement = () => {
	uni.navigateTo({
		url: '/pages/profile/ship-management'
	})
}

const goToPortServices = () => {
	uni.navigateTo({
		url: '/pages/profile/port-services'
	})
}

const goToCrewManagement = () => {
	uni.navigateTo({
		url: '/pages/profile/crew-management'
	})
}

const goToAddresses = () => {
	uni.navigateTo({
		url: '/pages/profile/address'
	})
}

const goToPaymentMethods = () => {
	uni.navigateTo({
		url: '/pages/profile/payment-methods'
	})
}

const goToInvoices = () => {
	uni.navigateTo({
		url: '/pages/profile/invoices'
	})
}

const goToCustomerService = () => {
	uni.navigateTo({
		url: '/pages/message/ai-chat'
	})
}

const goToFeedback = () => {
	uni.navigateTo({
		url: '/pages/profile/feedback'
	})
}

const goToHelp = () => {
	uni.navigateTo({
		url: '/pages/profile/help'
	})
}

const goToIdentityVerification = () => {
	// 点击认证菜单时先刷新状态
	loadUserData().then(() => {
		uni.navigateTo({
			url: '/pages/identity/verification'
		})
	}).catch(() => {
		// 即使刷新失败也要允许跳转
		uni.navigateTo({
			url: '/pages/identity/verification'
		})
	})
}

const getVerificationStatusClass = (status) => {
	switch (status) {
		case 'approved':
			return 'status-approved'
		case 'pending':
			return 'status-pending'
		case 'rejected':
			return 'status-rejected'
		default:
			return 'status-default'
	}
}

const getVerificationStatusText = (status) => {
	switch (status) {
		case 'approved':
			return '已认证'
		case 'pending':
			return '审核中'
		case 'rejected':
			return '已拒绝'
		default:
			return '未认证'
	}
}

const goToSettings = () => {
	uni.navigateTo({
		url: '/pages/profile/settings'
	})
}

const goToAbout = () => {
	uni.navigateTo({
		url: '/pages/profile/about'
	})
}

const goToLogin = () => {
	uni.navigateTo({
		url: '/pages/auth/login'
	})
}

// 退出登录
const logout = () => {
	uni.showModal({
		title: '确认退出',
		content: '确定要退出登录吗？',
		confirmText: '退出',
		cancelText: '取消',
		success: (res) => {
			if (res.confirm) {
				store.actions.logout()

				uni.reLaunch({
					url: '/pages/auth/login'
				})
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.profile-container {
	min-height: 100vh;
	background: #F5F5F5;
}

.profile-header {
	position: relative;
	height: 200px;
	margin-bottom: 15px;
}

.header-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}

.bg-image {
	width: 100%;
	height: 100%;
}

.header-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: linear-gradient(135deg, rgba(79, 172, 254, 0.8), rgba(0, 242, 254, 0.8));
}

.user-info {
	position: absolute;
	bottom: 20px;
	left: 0;
	right: 0;
	padding: 0 20px;
	display: flex;
	align-items: center;
	gap: 15px;
}

.avatar-section {
	position: relative;
}

.user-avatar {
	width: 70px;
	height: 70px;
	border-radius: 35px;
	border: 3px solid #FFFFFF;
}

.avatar-edit {
	position: absolute;
	bottom: -5px;
	right: -5px;
	width: 24px;
	height: 24px;
	background: var(--primary-color);
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 2px solid #FFFFFF;
}

.edit-icon {
	font-size: 12px;
	color: #FFFFFF;
}

.user-details {
	flex: 1;
}

.user-name {
	font-size: 20px;
	font-weight: bold;
	color: #FFFFFF;
	display: block;
	margin-bottom: 4px;
}

.user-role {
	font-size: 14px;
	color: rgba(255, 255, 255, 0.9);
	display: block;
	margin-bottom: 2px;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&:hover {
		color: #FFFFFF;
		text-decoration: underline;
	}
	
	&:active {
		transform: scale(0.98);
	}
}

.user-ship {
	font-size: 12px;
	color: rgba(255, 255, 255, 0.7);
	display: block;
}

.edit-profile {
	background: rgba(255, 255, 255, 0.2);
	border: 1px solid rgba(255, 255, 255, 0.3);
	border-radius: 15px;
	padding: 6px 12px;
	display: flex;
	align-items: center;
	gap: 4px;
}

.edit-text {
	font-size: 12px;
	color: #FFFFFF;
}

.edit-arrow {
	font-size: 10px;
	color: #FFFFFF;
}

.stats-section {
	background: #FFFFFF;
	margin-bottom: 15px;
	padding: 20px;
}

.stats-grid {
	display: flex;
	justify-content: space-around;
}

.stats-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.stats-number {
	font-size: 24px;
	font-weight: bold;
	color: var(--primary-color);
	margin-bottom: 6px;
}

.stats-label {
	font-size: 12px;
	color: #666666;
}

.order-section {
	background: #FFFFFF;
	margin-bottom: 15px;
	padding: 20px;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15px;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.section-more {
	font-size: 14px;
	color: var(--primary-color);
}

.order-shortcuts {
	display: flex;
	justify-content: space-around;
}

.order-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.order-icon {
	position: relative;
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 8px;
}

.icon {
	font-size: 18px;
}

.badge {
	position: absolute;
	top: -5px;
	right: -5px;
	background: #ff4757;
	color: #FFFFFF;
	font-size: 10px;
	padding: 2px 6px;
	border-radius: 10px;
	min-width: 16px;
	text-align: center;
}

.order-text {
	font-size: 12px;
	color: #666666;
}

.menu-section {

}

.menu-group {
	background: #FFFFFF;
	margin-bottom: 15px;
	overflow: hidden;
}

.group-title {
	font-size: 14px;
	color: #999999;
	padding: 15px 20px 10px;
	background: #F8F9FA;
	display: block;
}

.menu-list {

}

.menu-item {
	padding: 15px 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1px solid #F8F9FA;

	&:last-child {
		border-bottom: none;
	}

	&:active {
		background: #F8F9FA;
	}
}

.menu-left {
	display: flex;
	align-items: center;
	gap: 12px;
}

.menu-right {
	display: flex;
	align-items: center;
	gap: 8px;
}

.status-badge {
	font-size: 12px;
	padding: 2px 8px;
	border-radius: 10px;
	color: #FFFFFF;

	&.status-approved {
		background: #4CAF50;
	}

	&.status-pending {
		background: #FF9800;
	}

	&.status-rejected {
		background: #F44336;
	}

	&.status-default {
		background: #CCCCCC;
		color: #666666;
	}
}

.menu-icon {
	font-size: 18px;
	width: 20px;
	text-align: center;
}

.menu-text {
	font-size: 16px;
	color: #333333;
}

.menu-arrow {
	font-size: 14px;
	color: #CCCCCC;
}

.logout-section {
	padding: 20px;
}

.logout-btn {
	width: 100%;
	height: 50px;
	background: #FFFFFF;
	border: 1px solid #ff4757;
	border-radius: 25px;
	color: #ff4757;
	font-size: 16px;
	font-weight: 600;
}

.logout-text {
	color: #ff4757;
}

.version-info {
	text-align: center;
	padding: 10px 20px 30px;
}

.version-text {
	font-size: 12px;
	color: #CCCCCC;
}
</style>